﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using OBUCare.Core.Models;
using OBUCare.Core.Common;
using OBUCare.Core.DataAccess;
using OBUCare.Core.BL;
using OBUCare.Web.Infrastructure;
using Telerik.Web.Mvc;
using System.Collections.Specialized;
using OBUCare.Web.Models;

namespace OBUCare.Web.Controllers
{
    public class PartsController : Controller
    {
        //
        // GET: /Parts/
        ConfigMgr configMrg = new ConfigMgr();
        OBU_CAREContext db = new OBU_CAREContext();
        OBUCareOrderMgr obuMgr = new OBUCareOrderMgr();
        ISSUE_RPTContext issueDB = new ISSUE_RPTContext();
        static string partsName = "";

        static string fromAgent = "";
        static string toAgent = "";

        #region 入库


        public ActionResult Index()
        {
            return View();
        }
        public ActionResult ParentPage()
        {
            return View();
        }
        public ActionResult PartControl(int id)
        {
            return PartialView("PartControl", id);
        }

        public ActionResult StockInPrint(string id)
        {
            ViewBag.IDs = id;
            ViewBag.parts = partsName;
            return View();
        }

        [GridAction]
        public ActionResult ListStockInDetails(string id)
        {
            IEnumerable<View_PartsStockDetails> items = null;
            if (!id.IsNullOrEmpty())
            {
                var sqlWhere = string.Format(" ID in ({0})", id);

                items = this.obuMgr.GetPartsStockIn(sqlWhere); // db.Database.SqlQuery<View_PartsStockDetails>(sql).ToList();
            }

            var temp = new GridModel(items);
            return View(temp);
        }

        /// <summary>
        /// 入库
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Incoming(int PartType, int hidPartControlIndex, FormCollection form, string specAll)
        {
            partsName = "";
            try
            {
                var infos = new List<PARTS_STOCK>();

                string[] strs = specAll.Split(',').ToArray();
                for (int i = 0; i < hidPartControlIndex; i++)
                {
                    if (strs[i] != "undefined")
                    {
                        //在增加两行 界面一共为三行后，删除中间那行，最后一行的序列还是为3，所以循环的顺序不符合其要求
                        //则判断其是否有型号值
                        var info = getPartsStockInfo(PartType, form, i, strs[i].ToInt().Value);
                        if (info != null)
                        {
                            infos.Add(info);
                        }
                    }
                }

                obuMgr.PartsStockIn(infos);

                string ids = infos.Select(i => i.ID).ToList().ConcatToString(",");

                var partsInfo = db.PARTS_TYPE.Find(infos.FirstOrDefault().PARTS_ID);
                partsName = partsInfo.PARTS_NAME;
                return Json(new { success = true, message = "", ids = ids });
            }
            catch (Exception ex)
            {
                return Json(new { success = false, message = ex.Message });
            }
            finally
            {

            }
        }

        private PARTS_STOCK getPartsStockInfo(int PartType, FormCollection form, int index, int specID)
        {
            PARTS_STOCK info = null;
            if (form.AllKeys.Contains(ConfigMgr.Parts_Supplier + index.ToText()))
            {
                info = new PARTS_STOCK();
                var u = UIUtility.GetCurrentUser();
                info.CREATED_BY = u.OPERATOR_NO;
                info.CREATED_DATE = DateTime.Now;
                info.OWNER = new ISSUE_RPTContext().GetCenterAgentNo().AgentNo;
                info.PARTS_COUNT = form[ConfigMgr.Parts_Amount + index.ToText()].ToInt().Value;
                info.PARTS_ID = PartType;
                //info.PARTS_SPEC_ID=form[ConfigMgr.Parts_SpecName+index.ToText()].ToInt().Value;
                info.PARTS_SPEC_ID = specID;
                info.RECORD_DATE = form[ConfigMgr.Parts_RecordDate + index.ToText()].ToDateTime().Value;
                info.SPEC_NAME = configMrg.GetPartsSpec(info.PARTS_SPEC_ID).SPEC_NAME;
                info.status = DictTypeStatus.Normal.ToInt().Value;
                info.SUPPLIER_ID = form[ConfigMgr.Parts_Supplier + index.ToText()].ToInt().Value;
                info.SUPPLIER_NAME = configMrg.GetSupplier(info.SUPPLIER_ID).SHORTNAME;
            }
            return info;
        }

        #endregion

        #region 划拨

        private IList<View_PartsStock> getViewPartsStock(string id)
        {
            string[] strs = id.Split(',');
            string agentNo = strs[0];
            //划拨界面显示速通库存数量
            if (agentNo.IsNullOrEmpty())
                id = this.configMrg.GetCenterAgentNo().AgentNo;

            var items = (from p in db.View_PartsStock
                         where p.Owner == agentNo
                         orderby p.ID
                         select p).ToList();
            if (items != null && items.Count() > 0)
            {
                int i = 1;
                items.Each(e =>
                {
                    e.ID = i++;
                });
            }

            return items;
        }

        public ActionResult Transfer()
        {
            var centerAgent = this.configMrg.GetCenterAgentNo();
            var centerAgentNo = centerAgent.AgentNo;

            var items = getViewPartsStock(centerAgentNo);
            ViewBag.Items = items;
            return View(centerAgent);
        }



        public ActionResult TransferGridView(string id)
        {
            var items = getViewPartsStock(id);
            //var temp = new GridModel(items);
            return View(items);
        }

        /// <summary>
        /// 提交交接信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult ConfirmTransfer(string Agent, string sAgent, int ItemCount, string txtComments)
        {
            try
            {
                List<PARTS_TRANSFER> infos = new List<PARTS_TRANSFER>();

                for (int i = 1; i <= ItemCount; i++)
                {
                    var info = getPartsTransferInfo(this.Request.Form, i, Agent);
                    if (info != null)
                    {
                        info.Remark = txtComments;

                        infos.Add(info);
                    }
                }

                obuMgr.Transfer(infos);

                fromAgent = issueDB.GetAgentByNo(infos.FirstOrDefault().OWNER) != null ? issueDB.GetAgentByNo(infos.FirstOrDefault().OWNER).AgentName
                    : issueDB.GetCenterAgentNo().AgentName;
                toAgent = issueDB.GetAgentByNo(infos.FirstOrDefault().AGENT_NO) != null ? issueDB.GetAgentByNo(infos.FirstOrDefault().AGENT_NO).AgentName
                 : issueDB.GetCenterAgentNo().AgentName;

                string sIDs = infos.Select(i => i.ID).ConcatToString(",");
                string sql = string.Format("ID in ({0})", sIDs);
                return Json(new { success = true, message = "", sql = sql });
            }
            catch (Exception ex)
            {
                return Json(new { success = false, message = ex.Message });
            }
        }

        private PARTS_TRANSFER getPartsTransferInfo(NameValueCollection form, int index, string agent)
        {
            PARTS_TRANSFER info = null;
            if (form.AllKeys.Contains(ConfigMgr.Parts_ObjectInfo + index.ToText()))
            {
                int amount = form[ConfigMgr.Parts_Amount + index.ToText()].ToInt() == null ? 0 : form[ConfigMgr.Parts_Amount + index.ToText()].ToInt().Value;
                if (amount > 0)
                {
                    var objectInfo = HttpUtility.UrlDecode(form[ConfigMgr.Parts_ObjectInfo + index.ToText()]);
                    var obj = objectInfo.JsonDeserialize<View_PartsStock>();

                    var u = UIUtility.GetCurrentUser();
                    info = new PARTS_TRANSFER();
                    info.AGENT_NO = agent;
                    info.CREATED_BY = u.OPERATOR_NO;
                    info.CREATED_DATE = DateTime.Now;
                    info.OWNER = obj.Owner;
                    info.PARTS_COUNT = amount;
                    info.PARTS_ID = obj.PARTS_ID;
                    info.PARTS_SPEC_ID = obj.PARTS_SPEC_ID;
                    info.RECORD_DATE = DateTime.Now;
                    info.SPEC_NAME = obj.SPEC_NAME;
                    info.SUPPLIER_ID = obj.SUPPLIER_ID;
                    info.SUPPLIER_NAME = obj.SUPPLIER_NAME;
                    info.TRANSFER_KIND = Parts_Transfer_Kind.Transfer.ToInt().Value;


                    info.Status = DictTypeStatus.Normal.ToInt().Value;
                }
            }
            return info;
        }

        ///// <summary>
        ///// 调库
        ///// </summary>
        ///// <param name="form"></param>
        ///// <param name="index"></param>
        ///// <param name="agent"></param>
        ///// <returns></returns>
        //private PARTS_TRANSFER getPartsTransfer(NameValueCollection form, int index, string agent)
        //{
        //    PARTS_TRANSFER info = null;
        //    if (form.AllKeys.Contains(ConfigMgr.Parts_ObjectInfo + index.ToText()))
        //    {
        //        int amount = form[ConfigMgr.Parts_Amount + index.ToText()].ToInt() == null ? 0 : form[ConfigMgr.Parts_Amount + index.ToText()].ToInt().Value;
        //        if (amount > 0)
        //        {
        //            var objectInfo = HttpUtility.UrlDecode(form[ConfigMgr.Parts_ObjectInfo + index.ToText()]);
        //            var obj = objectInfo.JsonDeserialize<View_PartsStock>();

        //            var u = UIUtility.GetCurrentUser();
        //            info = new PARTS_TRANSFER();
        //            info.OWNER = agent;
        //            info.CREATED_BY = u.OPERATOR_NO;
        //            info.CREATED_DATE = DateTime.Now;
        //            info.AGENT_NO = obj.Owner;
        //            info.PARTS_COUNT = -amount;
        //            info.PARTS_ID = obj.PARTS_ID;
        //            info.PARTS_SPEC_ID = obj.PARTS_SPEC_ID;
        //            info.RECORD_DATE = DateTime.Now;
        //            info.SPEC_NAME = obj.SPEC_NAME;
        //            info.SUPPLIER_ID = obj.SUPPLIER_ID;
        //            info.SUPPLIER_NAME = obj.SUPPLIER_NAME;
        //            info.TRANSFER_KIND = Parts_Transfer_Kind.Change.ToInt().Value;


        //            info.Status = DictTypeStatus.Normal.ToInt().Value;
        //        }
        //    }
        //    return info;
        //}

        //private PARTS_STOCK getPARTS_STCOKInfo(PARTS_TRANSFER tInfo)
        //{
        //    PARTS_STOCK info = new PARTS_STOCK();
        //    info.CREATED_BY = tInfo.CREATED_BY;
        //    info.CREATED_DATE = tInfo.CREATED_DATE;
        //    info.OWNER = tInfo.OWNER;
        //    info.PARTS_COUNT = -tInfo.PARTS_COUNT;
        //    info.PARTS_ID = tInfo.PARTS_ID;
        //    info.PARTS_SPEC_ID = tInfo.PARTS_SPEC_ID;
        //    info.RECORD_DATE = tInfo.RECORD_DATE;
        //    info.SPEC_NAME = tInfo.SPEC_NAME;
        //    info.status = DictTypeStatus.Normal.ToInt().Value;
        //    info.SUPPLIER_ID = tInfo.SUPPLIER_ID;
        //    info.SUPPLIER_NAME = tInfo.SUPPLIER_NAME;

        //    return info;
        //}

        public ActionResult TransferPrint(string id)
        {
            object sql = id;
            ViewBag.fromAgent = fromAgent;
            ViewBag.toAgent = toAgent;
            return View(sql);
        }



        #endregion

        #region 冲正

        /// <summary>
        ///划拨冲正(已撤销)
        /// </summary>
        /// <returns></returns>
        public ActionResult Reversal()
        {
            return View();
        }

        [GridAction]
        public ActionResult ListPartsTransfer(string sql, string searchSql)
        {
            try
            {
                var result = getPartsTransfers(sql, searchSql).ToList();
                var temp = new GridModel(result.OrderByDescending(r => r.CREATED_DATE));
                return View(temp);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 根据sql返回查询后可冲正交接记录
        /// </summary>
        /// <param name="sql"></param>
        /// <param name="searchSql"></param>
        /// <returns></returns>
        private IEnumerable<View_Parts_Transfer> getPartsTransfers(string sql, string searchSql)
        {
            string tempSql = "";
            //界面默认显示为当天的数据
            if (searchSql.IsNullOrEmpty())
                searchSql = " RECORD_DATE>='" + DateTime.Now.ToShortDateString() + "' AND RECORD_DATE<'" + DateTime.Now.AddDays(1).ToShortDateString() + "'";
            if ((!sql.IsNullOrEmpty()) && (!searchSql.IsNullOrEmpty()))
                tempSql = sql + " and " + searchSql;
            else
                tempSql = string.Format("{0} {1}", sql, searchSql);



            var result = obuMgr.GetPartsTransfers(tempSql);
            return result;
        }

        /// <summary>
        /// 冲正操作
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [GridAction]
        public JsonResult ConfirmReversal(int id)
        {
            try
            {
                var r = obuMgr.Reversal(id, UIUtility.GetCurrentUser());
                return Json(new { success = r, message = "" });
            }
            catch (Exception ex)
            {
                return Json(new { success = false, message = ex.Message });
            }
        }


        [HttpPost]
        public JsonResult ReversalSearch(DateTime? FromCreatedDate, DateTime? ToCreatedDate, string Supplier, string SpecName,
            string sAgentType, string sAgent, string AgentType, string Agent, string PartType, string TransferKind) //也可以用这种格式接收参数public ActionResult Search(FormCollection form)
        {
            try
            {
                var sql = obuMgr.GetSearhReversalSql(FromCreatedDate, ToCreatedDate,
                    Supplier.ChangAllTextToNull(), SpecName.ChangAllTextToNull(), AgentType.ChangAllTextToNull(),
                    sAgent.ChangAllTextToNull(), sAgentType.ChangAllTextToNull(),
                    Agent.ChangAllTextToNull(), PartType.ChangAllTextToNull(), TransferKind.ChangAllTextToNull());

                return Json(new { Sql = sql, Success = true, ErrorMsg = "" });
            }
            catch (Exception ex)
            {
                return Json(new { Sql = "", Success = false, ErrorMsg = ex.Message });
            }
        }
        #endregion

        #region 销售

        public ActionResult Sell()
        {
            return View();
        }


        private string CheckSpecAndCount(int partType, int supplier, int spec,int count)
        {
            int specCount = db.Database.SqlQuery<int>(string.Format("SELECT COUNT(1) FROM PARTS_SPECS WHERE PARTS_ID={0} AND ID={1} AND SUPPLIER_ID={2}", partType, spec, supplier)).FirstOrDefault();

            string msg = "true";
            if (specCount <= 0)
            {
                msg = "没有此型号的元器件，请重新选择！";
            }
            else
            {
                int? stockCount = getStockNumBy(partType, spec.ToString()).Data.GetValue("StockCount").ToInt();
                if (stockCount == null || stockCount < count)
                {
                    msg = "此型号的元器件库存不足！";
                }
            }
            return msg;
        }

        [HttpPost]
        public JsonResult ConfirmSell(List<PartsSellInfo> data)
        {
            var user = UIUtility.GetCurrentUser();

            try
            {
                JsonResult jr = null;
                data.Each(d =>
                    {
                        string result = CheckSpecAndCount(d.PartTypeID, d.SupplierID, d.SpecID,data.Count);
                        if (result != "true")
                        {
                            jr = Json(new { success = false, message = result, userNO = "" });
                        }
                    });
                if (jr == null)
                {
                    var logID = obuMgr.SellParts(data, user);
                    var r = obuMgr.getObuInfoByObu(data[0].Obu_No);
                    // string[] strs =issueDB.getObuInfoByObu(data[0].Obu_No);
                    //var obuInfo = obuMgr.GetObuInfo(data[0].Obu_No);
                    return Json(new { success = true, message = "", userNO = r.USER_NO });
                }
                else
                {
                    return jr;
                }

            }
            catch (Exception ex)
            {
                return Json(new { success = false, message = ex.GetErrorMessage(), userNO = "" });
            }

        }


        public JsonResult GetObuInfo(string id)
        {
            object jsonInfo = null;
            try
            {
                string obuNo = id;
                //var info = obuMgr.GetObuInfo(obuNo);

                // string[] strs =issueDB.getObuInfoByObu(obuNo);
                //string registe_date = "";
                //string user_no = "";
                //string last_obu_no = "";

                var r = obuMgr.getObuInfoByObu(obuNo);

                //OBU_NO,REGISTE_DATE,USER_NO,LAST_OBU_NO
                #region 针对标签的发行时间重新获取，如有标签做过更换，则获取更换前的标签发行时间
                //string registe_date = strs[1];
                ////string user_no = strs[2];
                ////string last_obu_no = strs[3].Trim();
                if (r.LAST_OBU_NO != "")
                {
                    string lastNo = r.LAST_OBU_NO;
                    while (true)
                    {
                        var obuInfo = new ISSUE_RPTContext().getRegisteBy(lastNo, r.USER_NO);
                        if (obuInfo != null)
                        {
                            if (obuInfo.LAST_OBU_NO != null && obuInfo.LAST_OBU_NO.Trim() != "")
                            {
                                //如果还有更换信息，则继续
                                lastNo = obuInfo.LAST_OBU_NO;
                                continue;
                            }
                            else
                            {
                                //如果没有更换信息，则获取最早的发行日期
                                r.REGISTE_DATE = obuInfo.REGISTE_DATE;
                                //info.REGISTE_DATE = obuInfo.REGISTE_DATE;
                                break;
                            }
                        }
                        else
                        {
                            break;
                        }
                    }

                }
                #endregion

                var specInfo = (from i in db.PARTS_SPECS_DETAIL.ToList()
                                where Convert.ToInt64(i.START_NO) <= Convert.ToInt64(obuNo)
                               && Convert.ToInt64(i.END_NO) >= Convert.ToInt64(obuNo) && i.STATUS == DictTypeStatus.Normal.ToInt().Value
                                select i).FirstOrDefault();
                var spec = "请选择";
                var supplierID = "请选择";
                var partsType = "请选择";
                int? stockCount = 0;
                IList<SelectListItem> specList = null;
                if (specInfo != null)
                {
                    spec = specInfo.PARTS_SPEC_ID.ToString();
                    var supplier = (from i in db.PARTS_SPECS.ToList()
                                    where i.ID == specInfo.PARTS_SPEC_ID
                                    select i).FirstOrDefault();
                    supplierID = supplier.SUPPLIER_ID.ToString();
                    partsType = supplier.PARTS_ID.ToString();
                    stockCount = getStockNumBy(supplier.PARTS_ID, spec.ToString()).Data.GetValue("StockCount").ToInt();
                    specList = getSpecs(Convert.ToInt32(supplierID), supplier.PARTS_ID);
                }
                jsonInfo = new { OubNo = obuNo, IssueDate = r.REGISTE_DATE == null ? DateTime.Now.ToShortDateString() : Convert.ToDateTime(r.REGISTE_DATE).ToShortDateString(), SpecList = specList, StockNum = stockCount, SupplierID = supplierID, Spec = spec, partsType = partsType, success = true, message = "" };


            }
            catch (Exception ex)
            {
                jsonInfo = new { OubNo = "", IssueDate = "", success = false, message = "标签号不存在" };

            }

            return Json(jsonInfo, JsonRequestBehavior.AllowGet);
        }


        /// <summary>
        /// 获取下拉列表的元器件价格
        /// </summary>
        /// <returns></returns>
        public JsonResult GetDDLPartsPrie(int id)
        {
            List<SelectListItem> List = new List<SelectListItem>();
            if (id != UIConstants.AllItemsValue)
            {
                var partType = db.PARTS_TYPE.Find(id);


                List.Add(new SelectListItem { Value = partType.PRICE.ToText(), Text = partType.PRICE.ToText() });
                List.Add(new SelectListItem { Value = "0", Text = "0" });

                return Json(List, JsonRequestBehavior.AllowGet);
            }
            else
            {
                List.Add(new SelectListItem { Value = "0", Text = "0" });

                return Json(List, JsonRequestBehavior.AllowGet);
            }
        }

        #endregion

        #region 入库冲正
        public ActionResult StockCallBack()
        {
            ViewBag.StockType = "1";
            ViewBag.Enable = false;
            IList<SelectListItem> list = new List<SelectListItem>();
            IList<SelectListItem> listNew = new List<SelectListItem>();
            list = new ObuDropDownListHlper().GetInStockBy(UIConstants.AllItems, true, new KeyValuePair<string, string>(UIConstants.AllItems, UIConstants.AllItems));
            foreach (var item in list)
            {
                if (item.Value == "1")
                    listNew.Add(item);
            }
            ViewBag.ListData = listNew;
            return View();
        }

        [GridAction]
        public ActionResult ListPartsStockIn(string sql, string searchSql)
        {
            var result = getPartsStockIn(sql, searchSql).ToList();
            result.OrderByDescending(o => o.CREATED_DATE);
            var temp = new GridModel(result);
            return View(temp);
        }

        /// <summary>
        /// 根据sql返回查询后可冲正交接记录
        /// </summary>
        /// <param name="sql"></param>
        /// <param name="searchSql"></param>
        /// <returns></returns>
        private IEnumerable<View_PartsStockDetails> getPartsStockIn(string sql, string searchSql)
        {
            string tempSql = "";
            if ((!sql.IsNullOrEmpty()) && (!searchSql.IsNullOrEmpty()))
                tempSql = sql + " and " + searchSql;
            else
                tempSql = string.Format("{0} {1}", sql, searchSql);

            //默认显示当天入库的信息(排除冲正信息)
            if (tempSql.Trim() == "")
                tempSql += " RECORD_DATE>='" + DateTime.Now.ToShortDateString() + "' and RECORD_DATE<'" + DateTime.Now.AddDays(1).ToShortDateString() + "'"
                    + " AND " + obuMgr.GetStrWhereByInStockBy("1"); ;


            var result = obuMgr.GetPartsStockIn(tempSql);

            return result;
        }

        [HttpPost]
        public JsonResult PartsStockInSearch(DateTime? FromCreatedDate, DateTime? ToCreatedDate, string Supplier, string SpecName,
            string PartType, string Stock_type) //也可以用这种格式接收参数public ActionResult Search(FormCollection form)
        {
            try
            {
                var sql = obuMgr.GetSearhPartsStockInSql(FromCreatedDate, ToCreatedDate,
                    Supplier.ChangAllTextToNull(), SpecName.ChangAllTextToNull(), PartType.ChangAllTextToNull(), Stock_type.ChangAllTextToNull());

                return Json(new { Sql = sql, Success = true, ErrorMsg = "" });
            }
            catch (Exception ex)
            {
                return Json(new { Sql = "", Success = false, ErrorMsg = ex.Message });
            }
        }

        /// <summary>
        /// 冲正操作
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult ConfirmCallBack(int ID)
        {
            try
            {
                //入库冲正
                var v = db.PARTS_STOCK.Find(ID);
                Int64 transferNum = 0;
                if (v != null)
                {
                    //获取当前库存
                    string sqlContent = " SELECT ISNULL(SUM(PARTS_COUNT),0)"
                           + " FROM PARTS_STOCK WHERE PARTS_ID='" + v.PARTS_ID + "'  AND PARTS_SPEC_ID='" + v.PARTS_SPEC_ID + "'"
                            + " AND OWNER='" + v.OWNER + "'";
                    object result = new DatabaseHelper().ExecuteScalarSql(sqlContent);
                    if (result != null)
                        transferNum = Convert.ToInt64(result);
                    if (v.PARTS_COUNT > transferNum)
                    {
                        return Json(new { success = false, message = "该库存已划拨，不允许操作冲正" });
                    }
                }
                var r = obuMgr.StockCallBack(ID, UIUtility.GetCurrentUser());
                return Json(new { success = r, message = "冲正成功" });
            }
            catch (Exception ex)
            {
                return Json(new { success = false, message = ex.Message });
            }
        }
        #endregion

        /// <summary>
        /// 获取当前营业厅库存数量(划拨-冲正-退库-销售)
        /// </summary>
        /// <returns></returns>
        public JsonResult getStockNumBy(int partID, string specID)
        {
            try
            {
                Int64 stockCount = 0;
                if (specID == "请选择" || specID == "0" || specID.Trim() == "")
                {
                    return Json(new { success = false, message = " ", StockCount = 0 });
                }
                else
                {
                    OPERATOR o = UIUtility.GetCurrentUser();


                    string sqlContent = " SELECT ISNULL(SUM(PARTS_COUNT),0)"
                        + " FROM PARTS_STOCK WHERE PARTS_ID='" + partID + "'  AND PARTS_SPEC_ID='" + specID + "'"
                         + " AND OWNER='" + o.AgentNo + "'";
                    object result = new DatabaseHelper().ExecuteScalarSql(sqlContent);
                    Int64 transferNum = 0;
                    if (result != null)
                        transferNum = Convert.ToInt64(result);

                    var sale = (from i in db.PARTS_SALE.ToList()
                                where i.PARTS_SPEC_ID == specID.ToInt() && i.AGENT_NO == o.AgentNo
                                && i.PARTS_ID == partID && i.STATUS == DictTypeStatus.Normal.ToInt().Value
                                select i).ToList();

                    stockCount = transferNum - sale.Count();

                    return Json(new { success = false, message = " ", StockCount = stockCount });
                }

            }
            catch (Exception ex)
            {

                return Json(new { success = false, message = "获取库存数量失败", StockCount = 0 });
            }

        }
        /// <summary>
        /// 根据厂商获取已配置好的型号信息
        /// </summary>
        /// <param name="supplierID"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult _getSpecs(string supplierID, string PartsType)
        {
            if (supplierID != "请选择" && PartsType != "请选择")
            {
                var result = new ObuDropDownListHlper().GetPartsSpecs(null, Convert.ToInt16(supplierID), Convert.ToInt16(PartsType), true);
                if (result.Count() == 0)
                    result.Add(new SelectListItem() { Value = "0", Text = "无" });
                else
                    result.Insert(0, new SelectListItem() { Value = "请选择", Text = "请选择" });
                return Json(new SelectList(result, "Value", "Text"), JsonRequestBehavior.AllowGet);
            }
            else
            {
                var list = new List<SelectListItem>();
                list.Insert(0, new SelectListItem() { Value = "请选择", Text = "请选择" });
                return Json(new SelectList(list, "Value", "Text"), JsonRequestBehavior.AllowGet);
            }
        }
        /// <summary>
        /// 根据厂商、元器件获取已配置好的型号名称
        /// </summary>
        /// <param name="supplierID"></param>
        /// <returns></returns>
        [HttpPost]
        public IList<SelectListItem> getSpecs(int supplierID, int PartsType)
        {
            var result = new ObuDropDownListHlper().GetPartsSpecs(null, supplierID, PartsType, true);
            if (result.Count() == 0)
                result.Add(new SelectListItem() { Value = "0", Text = "无" });
            else
            {
                result.Insert(0, new SelectListItem() { Value = "请选择", Text = "请选择" });
            }

            return result;
            // return Json(new SelectList(result, "Value", "Text"), JsonRequestBehavior.AllowGet);
        }

        #region 元器件销售信息管理（删除）

        public ActionResult SaleMgr()
        {
            return View();
        }
        [GridAction]
        public ActionResult ListPartsSale(string sql, string searchSql)
        {
            var result = getPartsSale(sql, searchSql).ToList();
            var temp = new GridModel(result.OrderByDescending(r => r.CREATED_DATE));
            return View(temp);
        }

        /// <summary>
        /// 根据sql返回查询后元器件销售记录
        /// </summary>
        /// <param name="sql"></param>
        /// <param name="searchSql"></param>
        /// <returns></returns>
        private IEnumerable<View_PARTS_SALE> getPartsSale(string sql, string searchSql)
        {
            //根据编号判断查询权限
            string whereAgentNo = Request["agentNO"] == null || Request["agentNO"].ToString() == "" ? "" : Request["agentNO"].ToString();
            string modelID = Request["menuNames"] == null || Request["menuNames"].ToString() == "" ? "" : Request["menuNames"].ToString();

            string tempSql = "";
            if ((!sql.IsNullOrEmpty()) && (!searchSql.IsNullOrEmpty()))
                tempSql = sql + " and " + searchSql;
            else
                tempSql = string.Format("{0} {1}", sql, searchSql);


            //如果最小权限为6 则增加操作员查询条件
            whereAgentNo = whereAgentNo == "" ? "" : " AND AGENT_NO='" + whereAgentNo + "'";
            OPERATOR operatorInfo = UIUtility.GetCurrentUser();
            string models = UIUtility.getOperatorByModule(operatorInfo, Convert.ToInt32(modelID));
            if (models == "6")
                whereAgentNo += " AND CREATED_BY='" + operatorInfo.OPERATOR_NO + "'";

            string normalSql = tempSql.Trim() == "" ?
            "  [REPORT_DATE]>='" + DateTime.Now.ToShortDateString() + "' AND [REPORT_DATE] <'" + DateTime.Now.AddDays(1).ToShortDateString() + "' " :
            "";//如果没有任何条件 则默认显示当天的所有信息

            var result = obuMgr.GetPartsSale(tempSql + normalSql + whereAgentNo);
            return result;
        }

        [HttpPost]
        public JsonResult PartsSaleSearch(DateTime? FromCreatedDate, DateTime? ToCreatedDate, string PartType,
            string Supplier, string SpecName, string AgentType, string Agent, string Operator, string ObuNo,
            string Amount) //也可以用这种格式接收参数public ActionResult Search(FormCollection form)
        {
            try
            {
                var sql = obuMgr.GetSearhPartsSaleSql(FromCreatedDate, ToCreatedDate, PartType.ChangAllTextToNull(), Supplier.ChangAllTextToNull(),
                    SpecName.ChangAllTextToNull(), AgentType.ChangAllTextToNull()
                    , Agent.ChangAllTextToNull(), Operator.ChangAllTextToNull(), ObuNo.ChangAllTextToNull().Trim(), Amount.ChangAllTextToNull().Trim());

                return Json(new { Sql = sql, Success = true, ErrorMsg = "" });
            }
            catch (Exception ex)
            {
                return Json(new { Sql = "", Success = false, ErrorMsg = ex.Message });
            }
        }

        [HttpPost]
        public ActionResult DeleteData(string ID, string Remark)
        {
            try
            {
                int id;
                if (int.TryParse(ID, out id))
                {
                    string msg;
                    string glParts = obuMgr.GetOtherRarts(id);
                    string invoiceInfo = obuMgr.GetOtherInvoice(obuMgr.GetOpertionIdByPartsId(id)) ? "此元器件信息的发票涉及其他业务流水，请重新提交其他流水的发票信息" : "";
                    if (obuMgr.DeleteParts(id, Remark, UIUtility.GetCurrentUser().OPERATOR_NO, UIUtility.GetCurrentUser().AgentNo, out msg))
                    {
                      
                        
                        return Json(new { Success = true, ErrorMsg = "删除成功" + glParts + invoiceInfo });
                    }
                    else
                    {
                        return Json(new { Success = false, ErrorMsg = "删除失败：" + msg });
                    }
                }
                else
                {
                    return Json(new { Success = false, ErrorMsg = "删除失败，ID为非整数" });
                }
            }
            catch (Exception ex)
            {
                return Json(new { Success = true, ErrorMsg = "未知错误，请联系管理员" });
            }
        }
        #endregion

        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            obuMgr.Dispose();
            configMrg.Dispose();
            base.Dispose(disposing);
        }
    }
}
